﻿using ACC.Data.Entities.Common;
using ACC.Extensions.ClientBusiness;
using ACC.Extensions.Entities;
using ACC.Extensions.PCClient.Helper;
using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ACC.Extensions.PCClient.View
{
    /// <summary>
    /// Interaction logic for ResultWithGridPicWnd.xaml
    /// </summary>
    public partial class ResultWithGridPicWnd : MetroWindow
    {
        public ResultWithGridPicWnd(string strBarcode, int inDefectLevel, bool bIsTest, GridPicDetail gridPicDetail, List<ClientFailureWord> lstStatusWordMenu)
        {
            InitializeComponent();
            this.Owner = Application.Current.MainWindow;
            this.txtBarcode.Text = strBarcode;
            _gridPicInfo = gridPicDetail;
            _listStatusWordMenu = lstStatusWordMenu;
            _strBarcode = strBarcode;
            _inDefectLevel = inDefectLevel;
            BitOK = 0;
            if (bIsTest)
            {
                this.chxTestPiece.IsChecked = true;
                this.chxTestPiece.IsEnabled = false;
            }

            this.btnOK.Content = string.Format(LanguageHelper.LoadStringFromResource("BTN_RESULT_OK"), System.Environment.NewLine);
            this.btnNOK.Content = string.Format(LanguageHelper.LoadStringFromResource("BTN_RESULT_NOK"), System.Environment.NewLine);
            this.btnHold.Content = string.Format(LanguageHelper.LoadStringFromResource("BTN_RESULT_HOLDE"), System.Environment.NewLine);
            this.btnOK.Visibility = Visibility.Visible;
            this.btnOK.IsEnabled = true;
        }
        public int BitOK { get; set; }
        private bool _bIsTest;
        private Thread _alarmThread;
        private bool _bAlarm;
        private bool _bIsRuning;
        private bool _bIsThreadRunning = false;
        private int _inDefectLevel;

        private List<ClientFailureWord> _listStatusWordMenu;
        private string _strBarcode;
        public string Barcode
        {
            get
            {
                return _strBarcode;
            }
            set
            {
                value = _strBarcode;
            }
        }

        private List<ClientFailureBit> _listStatusBit = new List<ClientFailureBit>();
        public List<ClientFailureBit> ListStatusBit
        {
            get
            {
                return _listStatusBit;
            }
            set
            {
                _listStatusBit = value;
            }
        }

        private GridPicDetail _gridPicInfo = new GridPicDetail();
        public GridPicDetail GridPicInfo
        {
            get
            {
                return _gridPicInfo;
            }
            set
            {
                _gridPicInfo = value;
            }
        }

        private UnloadVariable _unloadData;
        public UnloadVariable UnloadData {
            get {
                return _unloadData;
            }
            set
            {
                _unloadData = value;
            }
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.ctrGridPic.GridPicInfo = GridPicInfo;
            this.ctrGridPic.AddMenuItem(_listStatusWordMenu);
            this.ctrGridPic.MenuItemClickEvent += RefreshDataGrid;
            this.dbgReason.ItemsSource = ListStatusBit;

            StartAlarmThread();
            _bIsRuning = false;

            this.UseNoneWindowStyle = true;
            this.IgnoreTaskbarOnMaximize = true;
            this.WindowState = WindowState.Maximized;
        }

        private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //this.dbgReason.ItemsSource = null;
            //this.dbgReason.ItemsSource = ListStatusBit;
            ListStatusBit = ClientHelper.GetAllGridPicPositonInfo(this.ctrGridPic.cvsImgPic);
        }

        private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }
        private void RefreshDataGrid()
        {
            _bIsRuning = false;
            this.dbgReason.ItemsSource = null;
            this.dbgReason.ItemsSource = ClientHelper.GetAllGridPicPositonInfo(this.ctrGridPic.cvsImgPic);
            foreach (ClientFailureBit item in dbgReason.Items)
            {
                if (item.Bit > _inDefectLevel && !string.IsNullOrEmpty(item.Description))
                {
                    _bIsRuning = true;
                }
                if (IsNumberic(item.Description))
                { 
                    if (int.Parse(item.Description)>5)
                    {
                        _bIsRuning = true;
                    }
                }
            }
        }

        private UnloadVariable GetUnloadData(bool bIsOK)
        {
            ClientFailureBit statusBit = new ClientFailureBit();
            List<ClientFailureBit> lstStatusBit = new List<ClientFailureBit>();
            if (bIsOK)
            {
                statusBit.Bit = 1; //OK为1，NOK为0
                lstStatusBit.Add(statusBit);
                return new UnloadVariable() { IsTestUnit = _bIsTest, LstStatusBit = lstStatusBit };
            }
            else
            {
                foreach (ClientFailureBit item in this.dbgReason.Items)
                {
                    lstStatusBit.Add(item);
                }
                return new UnloadVariable() { IsTestUnit = _bIsTest, LstStatusBit = lstStatusBit };
            }
        }
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            BitOK = 1;
            _unloadData = GetUnloadData(true); //OK true ;NOK false
            DialogResult = true;
            this.Close();
        }

        private void btnNOK_Click(object sender, RoutedEventArgs e)
        {
            BitOK = 0;
            _unloadData = GetUnloadData(false); //OK true ;NOK false
            if (UnloadData.LstStatusBit.Count == 0)
            {
                MessageDialogWnd.ShowDialog(LanguageHelper.LoadStringFromResource("MSG_WARNING"), "请选择缺陷原因");
                return;
            }
            DialogResult = true;
            this.Close();
        }

        private void btnHold_Click(object sender, RoutedEventArgs e)
        {
            BitOK = 0;
            _unloadData = GetUnloadData(false); //OK true ;NOK false
            _unloadData.IsHold = true;
            if (UnloadData.LstStatusBit.Count == 0)
            {
                MessageDialogWnd.ShowDialog(LanguageHelper.LoadStringFromResource("MSG_WARNING"), "请选择缺陷原因");
                return;
            }
            DialogResult = true;
            this.Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            this.Close();
        }

        private void chxTestPiece_Click(object sender, RoutedEventArgs e)
        {
            UserValidateWnd wnd = new UserValidateWnd();
            wnd.Owner = this;
            var dialogResult = wnd.ShowDialog();
            if (dialogResult.HasValue && dialogResult.Value)
            {
                _bIsTest = this.chxTestPiece.IsChecked.Value;
                e.Handled = true;
            }
            else
            {
                this.chxTestPiece.IsChecked = _bIsTest;
                e.Handled = false;
            }
        }


        public void StartAlarmThread()
        {
            if (_alarmThread == null)
            {
                _bIsThreadRunning = true;
                _alarmThread = new Thread(new ThreadStart(HighLight));
                _bIsRuning = true;
                _alarmThread.IsBackground = true;
                _alarmThread.Start();
            }
            else
            {
                _bIsRuning = true;
            }

        }
        public void StopAlarmThread()
        {
            _bIsThreadRunning = false;
             if (_alarmThread != null)
            {
                _alarmThread.Join(1000);
                if (_alarmThread.IsAlive)
                    _alarmThread.Abort();
            }
            //Dispatcher.BeginInvoke(new Action(() =>
            //{
            //    this.txtAlarmMsg.Background = new SolidColorBrush(Colors.White);
            //    this.txtAlarmMsg.Text = "";
            //    this.btnOK.Visibility = Visibility.Visible;
            //    this.btnOK.IsEnabled = true;
            //}));
        }
        private void HighLight()
        {
            while (_bIsThreadRunning)
            {
                if (_bIsRuning == true)
                {
                    if (_bAlarm == false)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            this.txtAlarmMsg.Background = new SolidColorBrush(Colors.Yellow);
                            this.txtAlarmMsg.Text = string.Format( "缺陷等级超过{0}，请做报废！", _inDefectLevel);
                            this.btnOK.Visibility = Visibility.Hidden;
                            this.btnOK.IsEnabled = false;
                        }));
                        _bAlarm = true;
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            this.txtAlarmMsg.Background = new SolidColorBrush(Colors.Red);
                            this.txtAlarmMsg.Text = string.Format("缺陷等级超过{0}，请做报废！", _inDefectLevel);
                            this.btnOK.Visibility = Visibility.Hidden;
                            this.btnOK.IsEnabled = false;
                        }));
                        _bAlarm = false;
                    }
                    
                }
                else
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        txtAlarmMsg.Background = new SolidColorBrush(Colors.White);
                        this.txtAlarmMsg.Text = "";
                        this.btnOK.Visibility = Visibility.Visible;
                        this.btnOK.IsEnabled = true;
                    }));
                }
                Thread.Sleep(500);
            }
        }

        private bool IsNumberic(string strInput)
        {
            if (string.IsNullOrEmpty(strInput))
                return false;
            foreach (char c in strInput)
            {
                if (!char.IsDigit(c))
                    return false;
            }
            return true;
        }

        private void MetroWindow_Activated(object sender, EventArgs e)
        {
            UISession.IsWndActivated = this.IsActive;
        }

        private void MetroWindow_Deactivated(object sender, EventArgs e)
        {
            UISession.IsWndActivated = this.IsActive;
        }


    }
}
